<template>
  <div class="drawer-content-wrapper" v-loading="loading">
    <el-form
      ref="formRef"
      :model="contractForm"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="form-section-title">基本信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同名称" prop="name">
                <el-input v-model="contractForm.name" placeholder="请输入合同名称"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="合同编号" prop="code">
                <el-input v-model="contractForm.code" placeholder="请输入合同编号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="签约主体(乙方)" prop="subject_id">
                <el-select
                  v-model="contractForm.subject_id"
                  placeholder="请选择签约主体公司"
                  value-key="id"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in enterpriseList"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="合同类别" prop="cate_id">
                <el-select
                  v-model="contractForm.cate_id"
                  placeholder="请选择合同类别"
                  value-key="id"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in contractCategories"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="客户名称(甲方)" prop="customer">
                <el-input v-model="contractForm.customer" placeholder="请输入客户名称">
                  <template #append>
                    <el-button @click="selectCustomer">选择</el-button>
                  </template>
                </el-input>
                <input type="hidden" v-model="contractForm.customer_id" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户代表" prop="contact_name">
                <el-input
                  v-model="contractForm.contact_name"
                  placeholder="请输入客户代表姓名"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="客户联系电话">
                <el-input
                  v-model="contractForm.contact_mobile"
                  placeholder="请输入客户联系电话"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同金额" prop="cost">
                <el-input v-model="contractForm.cost" placeholder="请输入合同金额">
                  <template #prepend>¥</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="到账金额" prop="cost2">
                <el-input v-model="contractForm.cost2" placeholder="请输入到账金额">
                  <template #prepend>¥</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="后期服务费">
                <el-input
                  v-model="contractForm.cost3"
                  placeholder="请输入后期服务费"
                  type="textarea"
                  :rows="2"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同开始时间" prop="start_time">
                <el-date-picker
                  v-model="contractForm.start_time"
                  type="date"
                  placeholder="选择合同开始时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="合同结束时间" prop="end_time">
                <el-date-picker
                  v-model="contractForm.end_time"
                  type="date"
                  placeholder="选择合同结束时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 签订信息 -->
      <div class="form-section">
        <h3 class="form-section-title">签订信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同签订人" prop="sign_uid">
                <el-select
                  v-model="contractForm.sign_uid"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索用户"
                  :remote-method="remoteSearchUsers"
                  :loading="userLoading"
                  @change="handleUserChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in userOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                    <span>{{ item.name }}</span>
                    <span
                      v-if="item.department"
                      style="float: right; color: #8492a6; font-size: 13px"
                    >
                      {{ item.department }}
                    </span>
                  </el-option>
                </el-select>
                <input type="hidden" v-model="contractForm.sign_name" />
                <!-- 隐藏字段：合同所属部门 -->
                <input type="hidden" v-model="contractForm.did" />
                <input type="hidden" v-model="contractForm.sign_department" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <!-- 空列，保持布局 -->
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同签订日期" prop="sign_time">
                <el-date-picker
                  v-model="contractForm.sign_time"
                  type="date"
                  placeholder="选择合同签订日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <!-- 空列，保持布局 -->
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 附件信息 -->
      <div class="form-section">
        <h3 class="form-section-title">附件信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="合同附件">
                <el-upload
                  ref="uploadRef"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :on-remove="handleUploadRemove"
                  :file-list="fileList"
                  :auto-upload="true"
                  multiple
                  :limit="10"
                >
                  <el-button type="primary">选择文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">支持PDF、Word、Excel等格式</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 其他信息 -->
      <div class="form-section">
        <h3 class="form-section-title">其他信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="合同备注">
                <el-input
                  v-model="contractForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入合同备注"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>

    <!-- 客户选择对话框 -->
    <el-dialog
      v-model="customerDialogVisible"
      title="选择客户"
      width="800px"
      destroy-on-close
      append-to-body
      :close-on-click-modal="false"
      center
    >
      <div class="selector-container">
        <!-- 搜索区域 -->
        <div class="search-box">
          <el-input
            v-model="customerSearchKeywords"
            placeholder="请输入客户名称或联系方式搜索"
            clearable
            class="search-input"
            @keyup.enter="getCustomerList"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="getCustomerList">搜索</el-button>
        </div>

        <!-- 客户列表 -->
        <div class="table-container">
          <el-table
            :data="customerList || []"
            border
            height="400px"
            highlight-current-row
            row-key="id"
            empty-text="暂无数据"
            @row-click="handleCustomerRowClick"
          >
            <el-table-column type="index" width="60" label="序号" align="center" />
            <el-table-column prop="name" label="客户名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="contact_name" label="联系人" min-width="120" align="center" />
            <el-table-column
              prop="contact_mobile"
              label="联系电话"
              min-width="140"
              align="center"
            />
            <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-box">
          <el-pagination
            background
            v-model:current-page="customerQueryForm.page"
            v-model:page-size="customerQueryForm.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="customerTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleCustomerSizeChange"
            @current-change="handleCustomerCurrentChange"
          ></el-pagination>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="customerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCustomerSelect" :disabled="!selectedCustomer">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 部门选择对话框 -->
    <el-dialog
      v-model="departmentDialogVisible"
      title="选择部门"
      width="600px"
      destroy-on-close
      append-to-body
      :close-on-click-modal="false"
      center
    >
      <div class="selector-container">
        <!-- 部门列表 -->
        <div class="table-container">
          <el-table
            :data="departmentList || []"
            border
            height="400px"
            highlight-current-row
            row-key="id"
            empty-text="暂无数据"
            @row-click="handleDepartmentRowClick"
          >
            <el-table-column type="index" width="60" label="序号" align="center" />
            <el-table-column prop="title" label="部门名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="leader" label="部门负责人" min-width="120" align="center" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="departmentDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmDepartmentSelect"
            :disabled="!selectedDepartment"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import { contractApi } from '@/api/contract'
  import { cate } from '@/api/home/cate'
  import { customerApi } from '@/api/customer'
  import { userApi } from '@/api/user'

  // 定义属性
  const props = defineProps<{
    contractId: string
  }>()

  // 定义事件
  const emit = defineEmits<{
    (e: 'submit'): void
    (e: 'cancel'): void
  }>()

  // 路由
  const router = useRouter()
  const route = useRoute()

  // 表单引用
  const formRef = ref()

  // 加载状态
  const loading = ref(false)

  // 激活的Tab
  const activeTab = ref('basic')

  // 合同表单数据
  const contractForm = reactive({
    id: '',
    name: '',
    code: '',
    subject_id: '',
    cate_id: '',
    customer: '',
    customer_id: undefined,
    contact_name: '',
    contact_mobile: '',
    cost: '',
    cost2: '',
    cost3: '',
    // 初始化日期字段，使用当前日期的格式化字符串
    start_time: new Date().toISOString().split('T')[0],
    end_time: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 默认一年后
    sign_name: '',
    sign_uid: '',
    sign_department: '',
    did: '',
    sign_time: new Date().toISOString().split('T')[0], // 默认当前日期
    remark: '',
    types: 1, // 默认为销售合同类型
    file_ids: '', // 添加文件ID字段
  })

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
    subject_id: [{ required: true, message: '请选择签约主体公司', trigger: 'change' }],
    cate_id: [{ required: true, message: '请选择合同类别', trigger: 'change' }],
    customer: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    contact_name: [{ required: true, message: '请输入客户代表姓名', trigger: 'blur' }],
    cost: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
    cost2: [{ required: true, message: '请输入到账金额', trigger: 'blur' }],
    start_time: [{ required: true, message: '请选择合同开始时间', trigger: 'change' }],
    end_time: [{ required: true, message: '请选择合同结束时间', trigger: 'change' }],
    sign_uid: [{ required: true, message: '请选择合同签订人', trigger: 'change' }],
    // did 字段已设为隐藏，不再需要验证
    // did: [
    //   { required: true, message: '请选择合同所属部门', trigger: 'change' }
    // ],
    sign_time: [{ required: true, message: '请选择合同签订日期', trigger: 'change' }],
  }

  // 企业列表
  const enterpriseList = ref<any[]>([])

  // 合同分类列表
  const contractCategories = ref<any[]>([])

  // 客户列表相关
  const customerDialogVisible = ref(false)
  const customerSearchKeywords = ref('')
  const customerList = ref<any[]>([])
  const customerTotal = ref(0)
  const customerQueryForm = reactive({
    page: 1,
    limit: 10,
  })
  const selectedCustomer = ref<any>(null)

  // 用户远程搜索相关
  const userOptions = ref<any[]>([])
  const userLoading = ref(false)

  // 远程搜索用户
  const remoteSearchUsers = async (query: string) => {
    if (query === '') {
      userOptions.value = []
      return
    }

    userLoading.value = true
    try {
      const response = await userApi.getUserOptions({ keyword: query })

      if (response.code === 0 && response.data) {
        userOptions.value = response.data
      } else {
        userOptions.value = []
        ElMessage.warning(response.msg || '获取用户列表失败')
      }
    } catch (error) {
      userOptions.value = []
      ElMessage.error('获取用户列表失败')
    } finally {
      userLoading.value = false
    }
  }

  // 处理用户选择变更
  const handleUserChange = (userId: number) => {
    // 从选项中找到对应的用户
    const selectedUser = userOptions.value.find(item => item.id === userId)

    if (selectedUser) {
      // 设置用户名称
      contractForm.sign_name = selectedUser.name

      // 自动设置合同所属部门（隐藏字段）
      if (selectedUser.did) {
        contractForm.did = selectedUser.did
      }
      if (selectedUser.department) {
        contractForm.sign_department = selectedUser.department
      }

      ElMessage.success('用户选择成功')
    }
  }

  // 部门列表相关
  const departmentDialogVisible = ref(false)
  const departmentList = ref<any[]>([])
  const selectedDepartment = ref<any>(null)

  // 上传相关
  const uploadRef = ref()
  const uploadUrl = ref(import.meta.env.VITE_API_BASE_URL + '/home/files/upload')
  const uploadHeaders = ref({
    Authorization: 'Bearer ' + localStorage.getItem('token'),
  })
  const fileList = ref<any[]>([])

  // 上传成功处理
  const handleUploadSuccess = (response: any, file: any, files: any) => {
    if (response.code === 0 && response.data && response.data.id) {
      // 将上传成功的文件信息添加到fileList中
      const uploadedFile = {
        id: response.data.id,
        name: response.data.name,
        size: response.data.filesize,
        url: response.data.filepath,
      }

      // 更新fileList
      fileList.value = [...fileList.value, uploadedFile]

      // 更新合同表单的file_ids字段
      const fileIds = fileList.value.map((item: any) => item.id).join(',')
      contractForm.file_ids = fileIds

      ElMessage.success('文件上传成功')
    } else {
      ElMessage.error(response.msg || '文件上传失败')
    }
  }

  // 上传失败处理
  const handleUploadError = (error: any, file: any, fileList: any) => {
    ElMessage.error('文件上传失败')
  }

  // 文件移除处理
  const handleUploadRemove = (file: any, files: any) => {
    // 更新fileList
    fileList.value = files

    // 更新合同表单的file_ids字段
    const fileIds = fileList.value.map((item: any) => item.id).join(',')
    contractForm.file_ids = fileIds
  }

  // 返回上一页
  const goBack = () => {
    // 触发取消事件，而不是直接调用router.back()
    emit('cancel')
  }

  // 选择客户
  const selectCustomer = () => {
    getCustomerList()
    customerDialogVisible.value = true
  }

  // 选择部门
  const selectDepartment = () => {
    getDepartmentList()
    departmentDialogVisible.value = true
  }

  // 处理客户选择
  const handleCustomerSelect = (row: any) => {
    selectedCustomer.value = row
  }

  // 行点击处理客户选择
  const handleCustomerRowClick = (row: any) => {
    selectedCustomer.value = row
  }

  // 确认客户选择
  const confirmCustomerSelect = () => {
    if (selectedCustomer.value) {
      contractForm.customer = selectedCustomer.value.name
      contractForm.customer_id = selectedCustomer.value.id
      // 如果客户有联系人信息，自动填充
      if (selectedCustomer.value.contact_name) {
        contractForm.contact_name = selectedCustomer.value.contact_name
      }
      if (selectedCustomer.value.contact_mobile) {
        contractForm.contact_mobile = selectedCustomer.value.contact_mobile
      }
      customerDialogVisible.value = false
      ElMessage.success('客户选择成功')
    } else {
      ElMessage.warning('请先选择客户')
    }
  }

  // 处理部门选择
  const handleDepartmentSelect = (row: any) => {
    selectedDepartment.value = row
  }

  // 行点击处理部门选择
  const handleDepartmentRowClick = (row: any) => {
    selectedDepartment.value = row
  }

  // 确认部门选择
  const confirmDepartmentSelect = () => {
    if (selectedDepartment.value) {
      contractForm.sign_department = selectedDepartment.value.title
      contractForm.did = selectedDepartment.value.id
      departmentDialogVisible.value = false
      ElMessage.success('部门选择成功')
    } else {
      ElMessage.warning('请先选择部门')
    }
  }

  // 处理客户分页大小变化
  const handleCustomerSizeChange = (val: number) => {
    customerQueryForm.limit = val
    getCustomerList()
  }

  // 处理客户当前页变化
  const handleCustomerCurrentChange = (val: number) => {
    customerQueryForm.page = val
    getCustomerList()
  }

  // 提交表单
  const submitForm = () => {
    if (!formRef.value) return

    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          // 创建提交数据副本
          const submitData: any = { ...contractForm }

          // 确保合同类型字段存在且为数字类型
          if (submitData.types === undefined || submitData.types === null) {
            submitData.types = 1 // 默认为销售合同类型
          } else {
            // 确保是数字类型
            submitData.types = Number(submitData.types)
          }

          // 转换ID类字段为数字
          if (submitData.subject_id) {
            submitData.subject_id = Number(submitData.subject_id)
          }

          if (submitData.cate_id) {
            submitData.cate_id = Number(submitData.cate_id)
          }

          if (submitData.sign_uid) {
            submitData.sign_uid = Number(submitData.sign_uid)
          }

          if (submitData.did) {
            submitData.did = Number(submitData.did)
          }

          if (submitData.customer_id) {
            submitData.customer_id = Number(submitData.customer_id)
          }

          // 处理时间字段，确保时间字段可以被正确处理

          // 调用新后端接口更新合同信息
          const response: any = await contractApi.editContract(submitData)

          // 正确访问响应数据
          if (response?.code === 0) {
            // 触发父组件的submit事件，而不是调用goBack
            emit('submit')
          } else {
            ElMessage.error(response?.msg || '编辑合同失败')
          }
        } catch (error: any) {
          console.error('编辑合同错误:', error)
          // 显示详细错误信息
          if (error.response && error.response.data) {
            ElMessage.error(
              `编辑合同失败: ${error.response.data.message || JSON.stringify(error.response.data)}`
            )
          } else {
            ElMessage.error('编辑合同失败')
          }
        }
      }
    })
  }

  // 获取合同详情
  const getContractDetail = async (id: string) => {
    try {
      loading.value = true

      // 先获取合同详情，再加载选择器数据，避免重复请求
      const response: any = await contractApi.viewContract({ id })

      if (response?.code === 0) {
        const data = response.data

        // 处理时间字段，后端返回的是秒级时间戳，需要转换为前端控件需要的YYYY-MM-DD格式
        if (data.sign_time) {
          data.sign_time = formatTimestampToDate(data.sign_time)
        }

        if (data.start_time) {
          data.start_time = formatTimestampToDate(data.start_time)
        }

        if (data.end_time) {
          data.end_time = formatTimestampToDate(data.end_time)
        }

        // 填充表单数据
        Object.keys(contractForm).forEach(key => {
          if (data[key] !== undefined) {
            ;(contractForm as any)[key] = data[key]
          }
        })

        // 并行加载选择器数据，提高加载速度
        const [enterprisePromise, categoryPromise] = await Promise.allSettled([
          getEnterpriseList(),
          getContractCategories(),
        ])

        // 处理选择器加载结果
        if (enterprisePromise.status === 'rejected') {
          console.warn('企业列表加载失败，但继续处理合同数据')
        }

        if (categoryPromise.status === 'rejected') {
          console.warn('合同分类加载失败，但继续处理合同数据')
        }

        // 确保签约主体和合同类别正确设置
        if (data.subject_id) {
          contractForm.subject_id = data.subject_id // 保持数字类型，不转换为字符串

          // 如果有签约主体标题，确保其存在于企业列表中
          if (data.subject_title) {
            // 查找企业列表中是否已存在该签约主体（通过ID或标题）
            const existingSubject = enterpriseList.value.find(
              item => item.id === data.subject_id || item.title === data.subject_title
            )

            // 只有在完全不存在时才添加
            if (!existingSubject) {
              enterpriseList.value.push({
                id: data.subject_id,
                title: data.subject_title,
              })
            } else if (existingSubject.id !== data.subject_id) {
              // 如果标题相同但ID不同，更新ID以确保一致性
              existingSubject.id = data.subject_id
            }
          }
        }

        if (data.cate_id) {
          contractForm.cate_id = data.cate_id // 保持数字类型，不转换为字符串

          // 如果有合同类别标题，确保其存在于合同类别列表中
          if (data.cate_title) {
            // 查找合同类别列表中是否已存在该类别（通过ID或标题）
            const existingCategory = contractCategories.value.find(
              item => item.id === data.cate_id || item.title === data.cate_title
            )

            // 只有在完全不存在时才添加
            if (!existingCategory) {
              contractCategories.value.push({
                id: data.cate_id,
                title: data.cate_title,
              })
            } else if (existingCategory.id !== data.cate_id) {
              // 如果标题相同但ID不同，更新ID以确保一致性
              existingCategory.id = data.cate_id
            }
          }
        }

        // 处理附件信息 - 通过file_ids字段获取文件信息
        if (data.file_ids) {
          const fileIds = data.file_ids.split(',').filter((id: string) => id !== '')
          if (fileIds.length > 0) {
            try {
              // 批量获取文件信息
              const fileResponses = await Promise.all(
                fileIds.map(async (fileId: string) => {
                  const request = (await import('@/utils/request')).default
                  return await request({
                    url: `/home/files/public_view/${fileId}`,
                    method: 'get',
                  })
                })
              )

              // 过滤成功的响应并转换为上传组件需要的格式
              fileList.value = fileResponses
                .filter(response => response.code === 0 && response.data)
                .map(response => ({
                  id: response.data.id,
                  name: response.data.name,
                  size: response.data.filesize,
                  url: response.data.filepath,
                }))
            } catch (error) {
              fileList.value = []
            }
          }
        }

        // 加载用户详情，确保用户下拉框显示当前用户
        if (data.sign_uid) {
          try {
            const userResponse: any = await userApi.getUserOptions({
              keyword: data.sign_name || '',
            })
            if (userResponse.code === 0 && Array.isArray(userResponse.data)) {
              userOptions.value = userResponse.data
            }
          } catch (error) {
            console.warn('加载用户信息失败，但继续处理合同数据')
          }
        }
      } else {
        ElMessage.error(response?.msg || '获取合同详情失败')
      }
    } catch (error) {
      console.error('获取合同详情出错:', error)
      ElMessage.error('获取合同详情失败')
    } finally {
      loading.value = false
    }
  }

  // 将秒级时间戳转换为日期格式
  const formatTimestampToDate = (timestamp: number | string): string => {
    if (!timestamp) return ''

    const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp

    if (isNaN(ts) || ts <= 0) return ''

    const date = new Date(ts * 1000) // 将秒级时间戳转换为毫秒级
    return date.toISOString().split('T')[0] // 返回 YYYY-MM-DD 格式
  }

  // 获取企业列表
  const getEnterpriseList = async () => {
    // 如果已经有数据，避免重复请求
    if (enterpriseList.value.length > 0) {
      return enterpriseList.value
    }

    try {
      // 调用获取企业列表的接口
      const response: any = await cate.getEnterpriseList()

      if (response.code === 0) {
        let enterprises: any[] = []

        if (Array.isArray(response.data)) {
          enterprises = response.data
        } else if (response.data && typeof response.data === 'object' && response.data.list) {
          enterprises = response.data.list
        } else if (response.data && typeof response.data === 'object') {
          enterprises = Object.values(response.data)
        }

        // 确保所有项目都有id和title属性
        const normalizedEnterprises = enterprises.map((item: any) => {
          // 检查并标准化数据格式
          if (typeof item === 'object') {
            return {
              id: item.id || 0,
              title: item.title || item.name || '未命名企业',
            }
          }
          return item
        })

        // 直接设置列表，而不是合并
        enterpriseList.value = normalizedEnterprises

        return enterpriseList.value
      } else {
        ElMessage.error(response.msg || '获取企业列表失败')
        return []
      }
    } catch (error) {
      console.error('获取企业列表失败:', error)
      ElMessage.error('获取企业列表失败')
      enterpriseList.value = []
      return []
    }
  }

  // 获取合同分类列表
  const getContractCategories = async () => {
    // 如果已经有数据，避免重复请求
    if (contractCategories.value.length > 0) {
      return contractCategories.value
    }

    try {
      const response: any = await contractApi.getContractCategories()

      if (response.code === 0) {
        let categories: any[] = []

        if (Array.isArray(response.data)) {
          categories = response.data
        } else if (
          response.data &&
          typeof response.data === 'object' &&
          (response.data as any).list
        ) {
          categories = (response.data as any).list
        } else if (response.data && typeof response.data === 'object') {
          categories = Object.values(response.data)
        }

        // 确保所有分类都有id和title属性
        const normalizedCategories = categories.map((item: any) => {
          // 检查并标准化数据格式
          if (typeof item === 'object') {
            return {
              id: item.id || 0,
              title: item.title || item.name || '未命名类别',
            }
          }
          return item
        })

        // 直接设置列表，而不是合并
        contractCategories.value = normalizedCategories

        return contractCategories.value
      } else {
        ElMessage.error(response.msg || '获取合同分类失败')
        return []
      }
    } catch (error) {
      console.error('获取合同分类失败:', error)
      ElMessage.error('获取合同分类失败')
      contractCategories.value = []
      return []
    }
  }

  // 获取客户列表
  const getCustomerList = async () => {
    try {
      const params = {
        ...customerQueryForm,
        keywords: customerSearchKeywords.value,
      }
      const response: any = await customerApi.getCustomerList(params)

      if (response.code === 0) {
        // 根据API响应结构判断数据格式
        if (Array.isArray(response.data)) {
          // 如果数据是数组
          customerList.value = response.data
          customerTotal.value = response.data.length
        } else if (response.data && typeof response.data === 'object') {
          // 标准分页格式：{list: [...], total: 559, page: 1, limit: 10, pages: 56}
          if (response.data.list !== undefined) {
            customerList.value = response.data.list
            customerTotal.value = response.data.total || 0
          } else if (response.data.data !== undefined) {
            // 兼容格式：{data: [...], total: 559}
            customerList.value = Array.isArray(response.data.data) ? response.data.data : []
            customerTotal.value = response.data.total || 0
          } else {
            // 其他对象格式，转换为数组
            customerList.value = Object.values(response.data)
            customerTotal.value = response.data.total || response.data.count || 0
          }
        } else {
          // 如果数据为空或其他格式
          customerList.value = []
          customerTotal.value = 0
        }
      } else {
        ElMessage.error(response.msg || '获取客户列表失败')
        customerList.value = []
        customerTotal.value = 0
      }
    } catch (error) {
      console.error('获取客户列表错误:', error)
      ElMessage.error('获取客户列表失败')
      customerList.value = []
      customerTotal.value = 0
    }
  }

  // 获取部门列表
  const getDepartmentList = async () => {
    try {
      const response: any = await userApi.getDepartmentList()

      if (response.code === 0) {
        // 根据API响应结构判断数据格式
        if (Array.isArray(response.data)) {
          // 如果数据是数组
          departmentList.value = response.data
        } else if (
          response.data &&
          typeof response.data === 'object' &&
          (response.data as any).list
        ) {
          // 如果数据是对象并有list属性
          departmentList.value = (response.data as any).list
        } else if (response.data && typeof response.data === 'object') {
          // 如果数据是对象但没有list属性，转换为数组
          departmentList.value = Object.values(response.data)
        } else {
          // 如果数据为空或其他格式
          departmentList.value = []
        }
      } else {
        ElMessage.error(response.msg || '获取部门列表失败')
      }
    } catch (error) {
      console.error('获取部门列表错误:', error)
      ElMessage.error('获取部门列表失败')
      departmentList.value = []
    }
  }

  // 重置表单
  const resetForm = () => {
    if (!formRef.value) return

    formRef.value.resetFields()

    // 重新初始化时间字段
    // 仅在没有ID时（新建合同）设置默认时间，编辑时保留返回的时间值
    if (!contractForm.id) {
      contractForm.start_time = new Date().toISOString().split('T')[0]
      contractForm.end_time = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)
        .toISOString()
        .split('T')[0]
      contractForm.sign_time = new Date().toISOString().split('T')[0]
    }

    // 清空客户选择和用户选择
    selectedCustomer.value = null
    userOptions.value = []

    // 清空上传组件状态
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
    fileList.value = []
  }

  // 暴露给父组件的方法
  defineExpose({
    submitForm,
    resetForm,
  })

  // 加载合同数据
  const loadContractData = () => {
    if (props.contractId && props.contractId !== '') {
      getContractDetail(props.contractId)
    } else {
      ElMessage.error('缺少合同ID参数')
      goBack()
    }
  }

  // 监听contractId变化
  watch(
    () => props.contractId,
    (newId, oldId) => {
      if (newId && newId !== '' && newId !== oldId) {
        // 如果是新ID，直接加载数据，不在此处重置表单
        // 避免先清空后加载导致的短暂空白
        getContractDetail(newId)
      } else if (newId && newId !== '' && !oldId) {
        // 首次加载时
        getContractDetail(newId)
      }
    },
    { immediate: true }
  )
</script>

<style scoped>
  /* 抽屉内容容器 */
  .drawer-content-wrapper {
    height: 100%;
    overflow-y: auto;
    padding: 20px;
  }

  /* 表单部分 */
  .form-section {
    margin-bottom: 30px;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  }

  .form-section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-top: 0;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
  }

  .form-container {
    margin-bottom: 10px;
  }

  /* 选择器容器 */
  .selector-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .search-box {
    display: flex;
    margin-bottom: 15px;
    gap: 10px;
  }

  .search-input {
    width: 300px; /* 设置一个合适的固定宽度，不再占据所有剩余空间 */
  }

  .table-container {
    flex: 1;
    margin-bottom: 15px;
  }

  .pagination-box {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }

  /* 对话框页脚 */
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 12px;
  }

  /* 文件上传组件样式 */
  :deep(.el-upload-list) {
    width: 100%;
    max-height: none;
    overflow: visible;
  }

  :deep(.el-upload-list__item) {
    transition: all 0.3s;
  }

  /* 确保上传文件列表可以完全显示所有文件 */
  :deep(.el-upload-list--text) {
    max-height: none;
  }

  /* 优化对话框样式 */
  :deep(.el-dialog) {
    max-height: 90vh;
    margin: 0 auto !important;
  }

  :deep(.el-dialog__body) {
    max-height: 70vh;
    overflow-y: auto;
  }

  :deep(.el-dialog__wrapper) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
